package com.yy.base.servlet.upload;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import com.yy.base.util.SystemProperties;

public class UploadServlet extends HttpServlet {
	private static final long serialVersionUID = 7618658514199005769L;
	private FileUploadService fileUploadService = null;

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/plain");
		response.setHeader("Content-Type", "text/html;charset=UTF-8");
		response.addHeader("Access-Control-Allow-Origin", "*");
		request.setCharacterEncoding("utf-8");
		String path = SystemProperties.getValue("upload.path");
		
		String maxSize = request.getParameter("maxSize");
		fileUploadService = new FileUploadService();
		fileUploadService.setStoragePath(path);
		fileUploadService.setRetainFileName(true);
		fileUploadService.setServletContext(getServletContext());
		if (maxSize != null) {
			fileUploadService.setMaxSize(Long.parseLong(maxSize));
		}
		JSONArray array = new JSONArray();
		JSONObject json = null;
		try {
			for (File file : fileUploadService.getFilesInLocal(request)) {
				json = new JSONObject();
				json.put("name", file.getName());
				json.put("url", file.toString());
				json.put("size", file.length());
				json.put("type", file.getContentType());
				json.put("missing", file.isMissing());
				json.put("allowed", file.isAllowed());
				json.put("path", file.getPath());
				array.add(json);
			}
		} catch (Exception e) {
			json = new JSONObject();
			json.put("missing", true);
			array.add(json);
			e.printStackTrace();
		}
		PrintWriter out = response.getWriter();
		out.println(array.toString());
		out.flush();
		out.close();
	}
}